package com.ids.enigha;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.util.Date;
import java.util.Timer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Typeface;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.MapView;
import com.ids.enigha.R;

public class DisplayMapView extends FragmentActivity {

	public static TextView editTextShowLocation, hi_usernameTxt;
	public static Button disableButton, startservice, logout;
	public static EditText editCode;

	MapView mapView;
	int batterylevel;
	public static Timer t;
	public static String providerType;
	public static boolean timerFlag = false;
	public static String date;
	public static String IMEI = null;
	public static String phone = null;
	public static String URL_PATH = "http://192.237.167.247:9090/eNigha-trackingserver-1.0-SNAPSHOT/devices";

	DatabaseHelper dbh;
	Cursor cursor;
	public static String currentLat, currentLong;
	double latval, lonval, accval;
	public boolean pendingService = false;
	SharedPreferences sharedprefs;
	public static String timervalue;
	public static GoogleMap map;
	public static Double maplatitude, maplongitude;
	static Activity activity;
	public static FragmentManager fm;
	public static Fragment fr;
	public static SupportMapFragment mf;
	public static MarkerOptions mop;
	Context ctx;
	Marker marker;
	long currTime;
	Typeface face;
	public static boolean logFileFlag = true;
	MyLocation loc;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		face = Typeface.createFromAsset(this.getAssets(), "FrancoisOne.ttf");
		editTextShowLocation = (TextView) findViewById(R.id.editTextShowLocation);
		hi_usernameTxt = (TextView) findViewById(R.id.hi_usernameTxt);
		editCode = (EditText) findViewById(R.id.editTextcode);
		editCode.setVisibility(View.GONE);
		logout = (Button) findViewById(R.id.logout_btn);

		SharedPreferences myPrefs = DisplayMapView.this.getSharedPreferences(
				"ENIGHA_DETAILS", MODE_PRIVATE);
		String username = myPrefs.getString("username", "");
		hi_usernameTxt.setText(username);
		

		pDialog = new ProgressDialog(DisplayMapView.this);
		pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pDialog.setMessage("Please wait....");
		
		boolean isTrackingStarted = myPrefs.getBoolean("isTrackingStarted", false);
		loc = new MyLocation();
		if(!isTrackingStarted)
			loc.getCurrentLocation();

		try {
			MapsInitializer.initialize(getApplicationContext());
			fm = getSupportFragmentManager();
			System.out.println("raj 111111111111111111");
			fr = fm.findFragmentById(R.id.mapFrag);
			mf = (SupportMapFragment) fr;
			System.out.println("raj 2222222222222222");
			map = mf.getMap();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
		
		new FetchCurrentLocation().execute();
					
		logout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				turnGPSOff();
				currTime = new Date().getTime();
					
					Intent intentservice = new Intent(DisplayMapView.this, TrackingService.class);
					if (intentservice != null)
					{
						System.out.println("raj service stopped");
						stopService(intentservice);
						saveIsTrackingStarted(false);
						//new MyLocation(getApplicationContext()).removeUpdates();
						System.out.println("raj location updates stopped");
					}
					
				Intent inte = new Intent(DisplayMapView.this, LoginPage.class);
				inte.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(inte);
				finish();
			}
		});
		
	}
	
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		if (keyCode == KeyEvent.KEYCODE_BACK) {
//			// your code
//			return true;
//		}
//		return super.onKeyDown(keyCode, event);
//	}

	public String getLocationFromGPS(String latitude, String longitude) {

		String address = "";
		try {
			String url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="
					+ latitude + "," + longitude + "&sensor=true";

			Log.d("url", url);
			URL path = new URL(url);
			InputStream content = path.openStream();

			JSONObject outer = new JSONObject(convertStreamToString(content));

			if (outer != null) {
				JSONArray jArray = outer.getJSONArray("results");
				if (jArray.length() > 0) {
					JSONObject geo = jArray.getJSONObject(0);
					address = geo.getString("formatted_address");
					String[] splite = address.split(",");
					if (splite.length > 2)
						address = splite[0] + "," + splite[1];
					else {
						address = splite[0];
					}
					Log.d("addrs", address);
				}
			}
			return address;
		} catch (FileNotFoundException js) {

			return "Need Internet";

		} catch (JSONException js) {

			return "Need Internet";

		} catch (Exception e) {

			return "Need Internet";
		}
	}

	protected String convertStreamToString(InputStream is) throws IOException {

		if (is != null) {
			Writer writer = new StringWriter();

			char[] buffer = new char[10240];
			try {
				Reader reader = new BufferedReader(new InputStreamReader(is,
						"UTF-8"), 12);
				int n;
				while ((n = reader.read(buffer)) != -1) {
					writer.write(buffer, 0, n);
				}
			} finally {
				is.close();
			}
			return writer.toString();
		} else {
			return "";
		}
	}

	public void setUpMap(double lat, double lon, String address) {

		double lati = lat;
		double longi = lon;
		try {
			Log.d("updatemap", "update method");
			map.setMyLocationEnabled(true);
			if (marker != null) {
				marker.remove();
			}
			mop = new MarkerOptions().position(new LatLng(lati, longi))
					.title(address).snippet("");
			marker = map.addMarker(mop);
			marker.setPosition(new LatLng(lati, longi));
			//map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(lati, longi)));
			map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
					lati, longi), 18.0f));
		} catch (Exception e) {
			System.out.println("raj Exception in maps: "+e);
		}
	}

	public void turnGPSOn() {

		String provider = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		if (!provider.contains("gps")) {
			final Intent poke = new Intent();
			poke.setClassName("com.android.settings",
					"com.android.settings.widget.SettingsAppWidgetProvider");
			poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
			poke.setData(Uri.parse("3"));
			sendBroadcast(poke);
		}
	}

	private void turnGPSOff() {
		String provider = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

		if (provider.contains("gps")) { 
			final Intent poke = new Intent();
			poke.setClassName("com.android.settings",
					"com.android.settings.widget.SettingsAppWidgetProvider");
			poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
			poke.setData(Uri.parse("3"));
			sendBroadcast(poke);
		}
	}
	
	ProgressDialog pDialog;
	Location location = null;
	class FetchCurrentLocation extends AsyncTask<String, Void, Integer> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
				pDialog.show();			
		}

		@Override
		protected Integer doInBackground(String... params) {
			// TODO Auto-generated method stub
			int StatusCode = 0;
			location = loc.getCurrloc();
			System.out.println("raj current location for map: "+location);
			if(location != null)
			{				
				return 1;
			}
			
			return StatusCode;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			if(result == 1)
			{
				setUpMap(17.3836256, 78.428196, "");
				if (pDialog != null && pDialog.isShowing()) {
					pDialog.dismiss();
				}				
			}
			else
				new FetchCurrentLocation().execute();		
		}
	}
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();

	}

	public void saveIsTrackingStarted(boolean isTrackingStarted)
	{
		SharedPreferences prefs = getSharedPreferences("ENIGHA_DETAILS", MODE_PRIVATE);
		Editor editor = prefs.edit();
		editor.putBoolean("isTrackingStarted", isTrackingStarted);
		editor.commit();
	}
}
